import React, { Suspense, useReducer } from "react";
import { useEffect } from "react";
import { BrowserRouter, Link, Redirect, Route, Switch } from "react-router-dom";
import "./App.css";
import ErrorBoundry, { errorCatch } from "./components/ErrorBoundry";
import Foward from "./pages/lookfoward";
import FowardModal from "./pages/lookfoward/FowardModal";

import { AppContext, initData, reducer } from "./context";

import routerList, { RouterListProps } from "./Routes";
import Loading from "./components/Loading";

function App() {
  const [data, dispatch] = useReducer(reducer, initData);

  // 渲染组件父组件完成后，隐藏。对于 useEffect 和 useLayoutEffect 哪一个与 componentDidMount，componentDidUpdate
  useEffect(() => {
    // 加载资源后影藏。
    hide();
  }, []);

  /** beforeRouterEnter */
  const beforeRouterEnter = (props: RouterListProps, key: number) => {
    const { path, Component, name } = props;
    return (
      <Route
        path={path}
        render={() => (
          <ErrorBoundry text="页面出现异常" key={key}>
            <Component />
          </ErrorBoundry>
        )}
        key={key}
      />
    );
  };
  return (
    <ErrorBoundry>
      {/* context 可以提供多个值和操作方法。 */}
      <AppContext.Provider value={{ data, dispatch }}>
        <BrowserRouter basename="/manage">
          <Suspense fallback={<Loading />}>
            <Switch>
              {routerList.map((item, index) => beforeRouterEnter(item, index))}
              <Redirect from="/" to="/login" />
            </Switch>
          </Suspense>
        </BrowserRouter>
        <Foward ref={(ref) => ref && FowardModal.setOpenModal(ref)} />
      </AppContext.Provider>
    </ErrorBoundry>
  );
}

export default App;
